document.addEventListener("DOMContentLoaded", () => {
    const form = document.getElementById("add-article-form");
    const preview = document.getElementById("preview");
    const responseMessage = document.getElementById("response-message");

    // 图片预览功能
    window.previewImage = (event) => {
        const file = event.target.files[0];
        if (file) {
            if (file.size > 2 * 1024 * 1024) { // 限制图片大小为 2MB
                alert("图片大小不能超过 2MB");
                event.target.value = ""; // 清空文件输入
                return;
            }

            const reader = new FileReader();
            reader.onload = (e) => {
                preview.src = e.target.result;
                preview.style.display = "block";
            };
            reader.readAsDataURL(file);
        } else {
            preview.style.display = "none";
        }
    };

    // 表单提交
    form.addEventListener("submit", async (event) => {
        event.preventDefault();
   
        const title = form.querySelector("input[name='title']").value.trim();
        const content = form.querySelector("textarea[name='content']").value.trim();
        if (!title || !content) {
            responseMessage.textContent = "标题和内容为必填项！";
            responseMessage.style.color = "red";
            return;
        }
   
        const formData = new FormData(form);
   
        try {
            const response = await fetch("/submit_article", {
                method: "POST",
                body: formData,
                credentials: 'include' // 确保发送 Cookie
            });
   
            if (response.ok) {
                const result = await response.json();
                responseMessage.textContent = result.message;
                responseMessage.style.color = "green";
   
                form.reset();
                preview.style.display = "none";
            } else {
                const error = await response.json();
                responseMessage.textContent = error.message || "提交失败，请稍后再试。";
                responseMessage.style.color = "red";
            }
        } catch (error) {
            console.error("Error submitting article:", error);
            responseMessage.textContent = "提交失败，请稍后再试。";
            responseMessage.style.color = "red";
        }
    });
   
});
